<template>
    <el-drawer v-model="visible" :title="'test3-'+drawerName" direction="rtl" :destroy-on-close="true"
        @close="handleClose(ruleFormRef)">
        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px"
            class="demo-ruleForm" label-position="top">

            <el-form-item v-for="(field, index) in formFields" :key="index" :label="field.label" :prop="field.prop"
                :rules="[
                    {
                        required: true,
                        message: `请${field.type === 'select' ? '选择' : '输入'}${field.label}`,
                        trigger: field.type === 'select' ? 'change' : 'blur',
                    },
                ]">
                <el-input v-if="field.type === 'input'" v-model="ruleForm[field.prop]"></el-input>
                <el-input v-if="field.type === 'textarea'" v-model="ruleForm[field.prop]" type="textarea"></el-input>
                <el-select v-else-if="field.type === 'select'" v-model="ruleForm[field.prop]" placeholder="请选择">
                    <el-option v-for="option in field.options" :key="option.value" :label="option.label"
                        :value="option.value"></el-option>
                </el-select>
                <!-- 其他表单项 -->
            </el-form-item>

            <el-form-item v-if="drawerName !== '详情'">
                <el-button type="primary" @click="submitForm(ruleFormRef)" class="el-button--primary-i">提交</el-button>
                <el-button type="info" @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
</template>

<script setup>
import { ref, reactive, defineExpose } from "vue";

const visible = ref(false);
const drawerName = ref(""); // Drawer名称
const ruleFormRef = ref(); // 表单id
const ruleForm = ref({}); // 字段值
const formFields = ref([ // 字段列表
    {
        label: '用户名',
        prop: 'username',
        type: 'input'
    },
    {
        label: '密码',
        prop: 'password',
        type: 'input',
        password: true // 假设有这个属性表示密码输入框
    },
    {
        label: '描述',
        prop: 'desc',
        type: 'textarea',
    }
    // 更多字段...
]);

const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            console.log("submit!");
            console.log("提交的数据：");
            console.log(ruleForm.value);
        } else {
            console.log("error submit!");
            return false;
        }
    });
};

const resetForm = (formEl) => {
    if (!formEl) return;
    formEl.resetFields();
};

const handleClose = (formEl) => {
    if (!formEl) return;
    formEl.resetFields();
};

defineExpose({
    visible,
    drawerName, 
    ruleForm
})
</script>